package com.github.mvc.basic.service.impl;

import com.github.mvc.basic.entity.BaseEntity;
import com.github.mvc.basic.service.BaseService;
import com.github.session.LocalSession;
import com.github.session.SObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;

import java.util.Date;
import java.util.UUID;

@Service
public class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    private Mapper<T> mapper;

    @Override
    public Mapper getMapper() {
        return mapper;
    }

    @Override
    public int insert(T t) {
        initBaseInfo(t);
        return mapper.insert(t);
    }

    @Override
    public T getById(Object primaryKey) {
        return mapper.selectByPrimaryKey(primaryKey);
    }

    @Override
    public int update(T t) {
        initBaseInfo(t);
        return mapper.updateByPrimaryKey(t);
    }

    @Override
    public int delete(Object primaryKey) {
        return mapper.deleteByPrimaryKey(primaryKey);
    }

    private void initBaseInfo(T t) {
        if (t instanceof BaseEntity) {
            BaseEntity baseDto = (BaseEntity) t;
            baseDto.setId(UUID.randomUUID().toString());
            baseDto.setCreateTime(new Date());
            baseDto.setUpdateTime(new Date());
            SObject session = LocalSession.get();
            if (null != session) {
                baseDto.setCreateUserId(session.getUid());
                baseDto.setCreateOrgId(session.getOrgid());
                baseDto.setCreateUserId(session.getUid());
                baseDto.setUpdateOrgId(session.getOrgid());
            }
        }
    }
}
